package spring.cloud.tasks.executor.utils;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.KeeperException;

import java.util.List;

@Slf4j
@Setter
@Getter
public class CuratorFrameworkUtils {
    private CuratorFrameworkUtils() {
    }

    /**
     * Not use curator's deletingChildrenIfNeeded, to avoid this bug https://github.com/apache/curator/pull/235
     */
    public static void deleteRecursive(final CuratorFramework curatorFramework, final String path) throws Exception {
        List<String> children;
        try {
            children = curatorFramework.getChildren().forPath(path);
        } catch (KeeperException.NoNodeException e) {
            log.debug("no node exception throws during get children of path:" + path, e);
            return;
        }

        if (children != null) {
            for (String child : children) {
                deleteRecursive(curatorFramework, path + "/" + child);
            }
        }

        try {
            curatorFramework.delete().guaranteed().forPath(path);
        } catch (KeeperException.NotEmptyException e) {
            log.debug("try to delete path:" + path + " but fail for NotEmptyException", e);
            deleteRecursive(curatorFramework, path);
        } catch (KeeperException.NoNodeException e) {
            // When multi-client delete the children concurrently, then will throw such exception. So just do nothing.
            log.debug("try to delete path:" + path + " but fail for NoNodeException", e);
        }
    }

}
